# Whiskey Media Addon for XBMC v1.0.0
# Copyright (C) 2011 Anders Bugge
# 
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
# 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

# Contact Info
# E-Mail: whimais@gmail.com

# Thanks To
# http://www.whiskeymedia.com/
# http://www.giantbomb.com/
# http://www.comicvine.com/
# http://www.tested.com/
# http://www.screened.com/
# http://www.animevice.com/

_id='plugin.video.whiskeymedia'
_resdir = "special://home/addons/" + _id + "/resources"
_mediadir = _resdir + "/media/"

# API interface imports
sys.path.append(_resdir + "/lib/whimai")

# SYS imports
import sys
import urllib

# XBMC imports
import xbmc
import xbmcgui
import xbmcplugin
import xbmcaddon

# WhiMai
import video

# Load sites info
sites = video.getSites()

# Progress bar update callback
pDialog = None
def update_dialog_progess(pct):
	if pDialog != None:
		
		# Has update been canceled
		if pDialog.iscanceled():
			return False
		
		# if not update progress bar
		pDialog.update( pct )
		return True

def SITES():
	for i in range( len(sites) ):
		addSite(sites[i]['name'], sites[i]['id'], 1, _mediadir + sites[i]['image'])

def CATEGORIES(site):
	vb = video.VideoBase(int(site))
	categories = vb.getCategories()
	for i in range( len(categories) ):
		addCategory(categories[i]['name'],site,categories[i]['id'],2, _mediadir + sites[int(site)]['image'])

def VIDEOLINKS(site, cat, cat_name):
	vb = video.VideoBase(int(site))
	query = ""

	# Query needed?
	if int(cat) == vb.cat_search:
		keyboard = xbmc.Keyboard( "", "Search", False )
		keyboard.doModal()
		if ( keyboard.isConfirmed() ):
			query = keyboard.getText()

	# Get video quality setting
	vq = xbmcaddon.Addon(id=_id).getSetting('vq')
	if (vq == "1") :
		endString = "_1500.mp4"
	else:
		endString = "_700.mp4"

	# Get videos
	global pDialog
	pDialog = xbmcgui.DialogProgress()
	pDialog.create("Loading " + str(cat_name), "Retrieving data from " + str(sites[int(site)]['url']))
	print pDialog
		
	videos = vb.getVideos(int(cat),query,update_dialog_progess)
	print pDialog
	if videos == None:
		pDialog.close()
		del pDialog
		pDialog = None
		return False

	for i in range( len(videos) ):
		name	= videos[i]['name']
		url		= vb.media%{ 'url': videos[i]["url"].replace(".mp4",endString) }
		image	= videos[i]["image"]["super_url"]
		date	= videos[i]["publish_date"][8:10] + '-' + videos[i]["publish_date"][5:7] + '-' + videos[i]["publish_date"][0:4]
		deck	= videos[i]["deck"].encode('utf-8')
		addLink(name,site_id,cat,url,image,date,deck)

	pDialog.close()
	del pDialog
	pDialog = None

	# Add sort methods
	xbmcplugin.addSortMethod(int(sys.argv[ 1 ]), xbmcplugin.SORT_METHOD_DATE)
	xbmcplugin.addSortMethod(int(sys.argv[ 1 ]), xbmcplugin.SORT_METHOD_LABEL_IGNORE_THE)
	return True

def get_params():
	param=[]
	paramstring=sys.argv[2]
	if len(paramstring)>=2:
		params=sys.argv[2]
		cleanedparams=params.replace('?','')
		if (params[len(params)-1]=='/'):
			params=params[0:len(params)-2]
		pairsofparams=cleanedparams.split('&')
		param={}
		for i in range(len(pairsofparams)):
			splitparams={}
			splitparams=pairsofparams[i].split('=')
			if (len(splitparams))==2:
				param[splitparams[0]]=splitparams[1]
	return param

def addLink(name,site_id,cat,url,iconimage,date,deck):
	liz=xbmcgui.ListItem(name, iconImage="DefaultVideo.png", thumbnailImage=iconimage)
	liz.setInfo( type="Video", infoLabels={ "Title": name , "Date": date, "Plot": deck} )
	ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=url,listitem=liz)
	return ok

def addCategory(name,site_id,cat,mode,iconimage):
	u=sys.argv[0]+"?site_id="+str(site_id)+"&cat="+str(cat)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)
	liz=xbmcgui.ListItem(name, iconImage="DefaultFolder.png", thumbnailImage=iconimage)
	liz.setInfo( type="Video", infoLabels={ "Title": name } )
	ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=True)
	return ok

def addSite(name,site_id,mode,iconimage):
	u=sys.argv[0]+"?site_id="+str(site_id)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)
	liz=xbmcgui.ListItem(name, iconImage="DefaultFolder.png", thumbnailImage=iconimage)
	liz.setInfo( type="Video", infoLabels={ "Title": name } )
	ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=True)
	return ok

# Get current selection
params=get_params()
site_id=None
cat=None
name=None
mode=None

try:
	site_id=urllib.unquote_plus(params["site_id"])
except:
	pass

try:
	cat=urllib.unquote_plus(params["cat"])
except:
	pass

try:
	name=urllib.unquote_plus(params["name"])
except:
	pass

try:
	mode=int(params["mode"])
except:
	pass

# Update selection
end_dir = True
if mode==None or site_id==None or len(site_id)<1:
	SITES()

elif mode==1:
	CATEGORIES(site_id)
	
elif mode==2:
	end_dir = VIDEOLINKS(site_id, cat, name)

if end_dir == True:
	xbmcplugin.endOfDirectory(int(sys.argv[1]))
